package com.apache.member.service.impl;

import java.util.List;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.member.entity.MemberRole;
import com.apache.member.entity.MemberTemp;
import com.apache.member.manager.MemberTempManager;

public class MemberTempManagerImpl implements MemberTempManager {

	protected IDao memberTempDao;
	protected final String entityName = "com.apache.member.entity.MemberTemp";
	protected final String memberRoleEntity = "com.apache.member.entity.MemberRole";
	protected final String noticeEntity = "com.apache.member.entity.Notice";
	protected final String auditEntity = "com.apache.member.entity.Audit";
	protected final String auditRuleEntity = "com.apache.member.entity.AuditRule";

	public void setMemberDao(IDao memberTempDao) {
		this.memberTempDao = memberTempDao;
	}

	public String saveInfo(ParamsVo<MemberTemp> vo) throws BusinessException {
		MemberTemp memberTemp = vo.getObj();
		String infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		memberTemp.setMemberId(infoId);
		MethodParam param = new MethodParam("MemberTemp", cacheKey, "", entityName);
		param.setVaule(memberTemp);

		if (memberTempDao.insert(param)) {
			return infoId;
		}
		return "";
	}

	/**
	 * 主键非自动生成，而是和member表中保存一致
	 * @see com.apache.member.manager.MemberTempManager#saveMemberTempInfo(com.apache.api.vo.ParamsVo)
	 */
	public String saveMemberTempInfo(ParamsVo<MemberTemp> vo) throws BusinessException {
		MemberTemp memberTemp = vo.getObj();
		String infoId = memberTemp.getMemberId();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		memberTemp.setMemberId(infoId);
		MethodParam param = new MethodParam("MemberTemp", cacheKey, "", entityName);
		param.setVaule(memberTemp);

		if (memberTempDao.insert(param)) {
			return infoId;
		}
		return "";
	}

	/**
	 * add by  yaojs 2015-06-16
	 * description:  
	 * @param vo
	 * @return
	 * @throws BusinessException  
	 * @author Administrator 
	 * @update 2015-6-16
	 */
	public String saveMemberRoleInfo(ParamsVo<MemberTemp> vo) throws BusinessException {
		MemberTemp memberTemp = vo.getObj();
		String infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		memberTemp.setMemberId(infoId);
		MethodParam param = new MethodParam("MemberTemp", cacheKey, "", entityName);
		param.setVaule(memberTemp);
		if (memberTempDao.insert(param)) {
			return saveMemberRoles(memberTemp, cacheKey);
		}
		return "";
	}

	/**
	 * 重构方法实现保存会员角色信息
	 * description:  保存会员的角色信息
	 * @param memberTemp : 会员对象
	 * @param cacheKey : 缓存key 
	 * @author yaojs 
	 * @update 2015-6-19
	 */
	public String saveMemberRoles(MemberTemp memberTemp, String cacheKey) {
		if (null != memberTemp.getMemberRoles() && !"".equals(memberTemp.getMemberRoles())) {
			String memberRoles = memberTemp.getMemberRoles();
			String[] roles = memberRoles.split(",");
			for (String s1 : roles) {
				MemberRole memberRole = new MemberRole();
				memberRole.setMemberId(memberTemp.getMemberId());
				memberRole.setRoleCname(s1);
				memberRole.setRoleId(Validator.generate());
				MethodParam param1 = new MethodParam("MemberRole", cacheKey, "", memberRoleEntity);
				param1.setVaule(memberRole);
				if (!memberTempDao.insert(param1)) {
					return "";
				}
			}
		}
		return memberTemp.getMemberId();
	}

	public boolean editInfo(ParamsVo<MemberTemp> vo) throws BusinessException {
		MemberTemp memberTemp = vo.getObj();
		if (Validator.isNotNull(memberTemp.getMemberId())) {
			String cacheKey = "";
			//String cacheKey="member_"+memberTemp.getMemberId();
			MethodParam param = new MethodParam("MemberTemp", cacheKey, "", entityName);
			param.setVaule(memberTemp);
			return memberTempDao.edit(param);
		}
		return false;
	}

	/**
	 * 更新member的基础信息和角色信息 ，事务控制不安全(因为在此之前会调用controller的deleteMemberRole方法)
	 * description:  
	 * @param vo
	 * @return
	 * @throws BusinessException  
	 * @author Administrator 
	 * @update 2015-6-17
	 */
	public boolean editMemberInfoAndRole(ParamsVo<MemberTemp> vo) throws BusinessException {
		MemberTemp memberTemp = vo.getObj();
		if (Validator.isNotNull(memberTemp.getMemberId())) {
			String cacheKey = "";
			//String cacheKey="member_"+memberTemp.getMemberId();
			MethodParam param = new MethodParam("MemberTemp", cacheKey, "", entityName);
			param.setVaule(memberTemp);
			if (memberTempDao.edit(param)) {
				String flag = saveMemberRoles(memberTemp, cacheKey);
				if (!"".equals(flag)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 更新member的基础信息和角色信息，事务控制安全 
	 * description:  
	 * @param vo
	 * @return
	 * @throws BusinessException  
	 * @author Administrator 
	 * @update 2015-6-17
	 */
	public boolean editMemberInfoAndRoleInOneMethod(ParamsVo<MemberTemp> vo) throws BusinessException {
		MemberTemp memberTemp = vo.getObj();
		if (Validator.isNotNull(memberTemp.getMemberId())) {
			String cacheKey = "";
			// 根据member中memberRoles是否为空，执行该操作
			if (Validator.isNotNull(memberTemp.getMemberRoles())) {
				boolean flag1 = deleteMemberRoles(memberTemp, cacheKey);
				if (!flag1) {
					return false;
				}
			}
			//String cacheKey="member_"+memberTemp.getMemberId();
			MethodParam param = new MethodParam("MemberTemp", cacheKey, "", entityName);
			param.setVaule(memberTemp);
			if (memberTempDao.edit(param)) {
				String flag = saveMemberRoles(memberTemp, cacheKey);
				if (!"".equals(flag)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 重构方法：根据member中memberRoles是否为空，执行该操作
	 * description:  
	 * @param memberTemp
	 * @param cacheKey  
	 * @author yaojs 
	 * @update 2015-6-19
	 */
	public boolean deleteMemberRoles(MemberTemp memberTemp, String cacheKey) {
		MethodParam param2 = new MethodParam("ByProperty", cacheKey, "", memberRoleEntity);
		param2.setParams("memberId", memberTemp.getMemberId());
		@SuppressWarnings("unchecked")
		List<MemberRole> oddRoleList = memberTempDao.select(param2);
		if (!Validator.isEmpty(oddRoleList)) {
			for (MemberRole mr : oddRoleList) {
				MethodParam param4 = new MethodParam("ById", cacheKey, "", memberRoleEntity);
				param4.setInfoId(mr.getRoleId());
				MemberRole info = (MemberRole) memberTempDao.selectById(param4);
				if (Validator.isEmpty(info)) {
					continue;
				}
				param4.setVaule(info);
				// 当前行必须加上否则报错
				param4.setParams("roleId", mr.getRoleId());
				param4.setDelete(true);
				if (!memberTempDao.delete(param4)) {
					return false;
				}
			}
		}
		return true;
	}

	public boolean deleteInfo(ParamsVo<MemberTemp> vo) throws BusinessException {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			return false;
		}
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		MemberTemp info = (MemberTemp) memberTempDao.selectById(param);
		if (Validator.isEmpty(info)) {
			return false;
		}
		param.setVaule(info);//此处需要先将状态值赋值为删除状态
		if ("false".equals(mark)) {//逻辑删除
			param.setKey("MemberTemp");
			return memberTempDao.edit(param);
		} else {
			param.setParams("memberId", infoId);
			param.setDelete(true);
			return memberTempDao.delete(param);
		}
	}

	public Object getInfoById(ParamsVo<MemberTemp> vo) {
		String infoId = vo.getInfoId();
		String cacheKey = "";
		//String cacheKey="member_"+infoId;
		if (Validator.isNull(infoId)) {
			return null;
		}
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		return memberTempDao.selectById(param);
	}

	public Object execute(ParamsVo<MemberTemp> vo) {
		return null;
	}

	public Page getPageInfo(ParamsVo<MemberTemp> vo) {
		MethodParam param = setMethodParams(vo, 2);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		Page page = memberTempDao.pageSelect(param);
		return page;
	}

	@SuppressWarnings("unchecked")
	public List<MemberTemp> getList(ParamsVo<MemberTemp> vo) {
		MethodParam param = setMethodParams(vo, 2);
		return memberTempDao.select(param);
	}

	public long countInfo(ParamsVo<MemberTemp> vo) {
		MethodParam param = setMethodParams(vo, 1);
		return memberTempDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<MemberTemp> vo, int type) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		StringBuffer sb = new StringBuffer(memberTempDao.getSql(type));
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		MemberTemp memberTemp = vo.getObj();
		if (Validator.isNotNull(memberTemp.getMemberId())) {
			sb.append(" and memberId = :memberId");
			param.setParams("memberId", memberTemp.getMemberId());
		}
		if (Validator.isNotNull(memberTemp.getMemberEname())) {
			sb.append(" and memberEname = :memberEname");
			param.setParams("memberEname", memberTemp.getMemberEname());
		}
		if (Validator.isNotNull(memberTemp.getMemberCname())) {
			sb.append(" and memberCname = :memberCname");
			param.setParams("memberCname", memberTemp.getMemberCname());
		}
		if (Validator.isNotNull(memberTemp.getShortName())) {
			sb.append(" and shortName = :shortName");
			param.setParams("shortName", memberTemp.getShortName());
		}
		if (Validator.isNotNull(memberTemp.getMemberType())) {
			sb.append(" and memberType = :memberType");
			param.setParams("memberType", memberTemp.getMemberType());
		}
		if (Validator.isNotNull(memberTemp.getOrgType())) {
			sb.append(" and orgType = :orgType");
			param.setParams("orgType", memberTemp.getOrgType());
		}
		if (Validator.isNotNull(memberTemp.getMobile())) {
			sb.append(" and mobile = :mobile");
			param.setParams("mobile", memberTemp.getMobile());
		}
		if (Validator.isNotNull(memberTemp.getPhone())) {
			sb.append(" and phone = :phone");
			param.setParams("phone", memberTemp.getPhone());
		}
		if (Validator.isNotNull(memberTemp.getEmail())) {
			sb.append(" and email = :email");
			param.setParams("email", memberTemp.getEmail());
		}
		if (Validator.isNotNull(memberTemp.getRegTime())) {
			sb.append(" and regTime = :regTime");
			param.setParams("regTime", memberTemp.getRegTime());
		}
		if (Validator.isNotNull(memberTemp.getClientManager())) {
			sb.append(" and clientManager = :clientManager");
			param.setParams("clientManager", memberTemp.getClientManager());
		}
		if (Validator.isNotNull(memberTemp.getCertType())) {
			sb.append(" and certType = :certType");
			param.setParams("certType", memberTemp.getCertType());
		}
		if (Validator.isNotNull(memberTemp.getCertNo())) {
			sb.append(" and certNo = :certNo");
			param.setParams("certNo", memberTemp.getCertNo());
		}
		if (Validator.isNotNull(memberTemp.getValidityPeriod())) {
			sb.append(" and validityPeriod = :validityPeriod");
			param.setParams("validityPeriod", memberTemp.getValidityPeriod());
		}
		if (Validator.isNotNull(memberTemp.getMemberLevel())) {
			sb.append(" and memberLevel = :memberLevel");
			param.setParams("memberLevel", memberTemp.getMemberLevel());
		}
		if (Validator.isNotNull(memberTemp.getInfoFrom())) {
			sb.append(" and infoFrom = :infoFrom");
			param.setParams("infoFrom", memberTemp.getInfoFrom());
		}
		if (Validator.isNotNull(memberTemp.getCreateUserEname())) {
			sb.append(" and createUserEname = :createUserEname");
			param.setParams("createUserEname", memberTemp.getCreateUserEname());
		}
		if (Validator.isNotNull(memberTemp.getCreateTime())) {
			sb.append(" and createTime = :createTime");
			param.setParams("createTime", memberTemp.getCreateTime());
		}
		if (Validator.isNotNull(memberTemp.getUpdateUserEname())) {
			sb.append(" and updateUserEname = :updateUserEname");
			param.setParams("updateUserEname", memberTemp.getUpdateUserEname());
		}
		if (Validator.isNotNull(memberTemp.getUpdateTime())) {
			sb.append(" and updateTime = :updateTime");
			param.setParams("updateTime", memberTemp.getUpdateTime());
		}
		if (Validator.isNotNull(memberTemp.getStatus())) {
			sb.append(" and status = :status");
			param.setParams("status", memberTemp.getStatus());
		}
		if (Validator.isNotNull(memberTemp.getAuditStatus())) {
			sb.append(" and auditStatus = :auditStatus");
			param.setParams("auditStatus", memberTemp.getAuditStatus());
		}

		param.setSqlStr(sb.toString());
		return param;
	}

	//	@Override
	//	public boolean editMemberTempInfoAndNotice(ParamsVo<MemberTemp> bmiVo) {
	//		MemberTemp memberTemp = bmiVo.getObj();
	//		if (Validator.isNotNull(memberTemp.getMemberId())) {
	//			String cacheKey = "";
	//			//String cacheKey="member_"+memberTemp.getMemberId();
	//			MethodParam param = new MethodParam("MemberTemp", cacheKey, "", entityName);
	//			memberTemp.setUpdateTime(DateUtil.getNowTime());
	//			LoginUser loginUser = (LoginUser) bmiVo.getParams("loginUser");
	//			memberTemp.setUpdateUserEname(loginUser.getUserEname());
	//			String auditType = (String) bmiVo.getParams("auditType");
	//			// 修改类型
	//			String editType = (String) bmiVo.getParams("editType");
	//			//暂存则不修改数据
	//			if ("0".equals(editType)) {
	//				param.setVaule(memberTemp);
	//				return memberTempDao.edit(param);
	//			} else {
	//				// 1.查询审核表中是否有审核数据
	//				param.setVaule(memberTemp);
	//				memberTemp.setAuditStatus(ConstantData.AuditStatus.AUDITING);
	//				String tableName = (String) bmiVo.getParams("tableName");
	//				MethodParam param1 = new MethodParam("ByProperty", "", "", auditEntity);
	//				param1.setParams("pid", memberTemp.getMemberId());
	//				param1.setParams("tableName", tableName);
	//				param1.setParams("status", ConstantData.AuditStatus.AUDITING);
	//				List<Audit> auditList = memberTempDao.select(param1);
	//				// 审核表有数据，不用回滚，返回false
	//				if (!Validator.isEmpty(auditList)) {
	//					return false;
	//				} else {
	//					// 2.查询审核规则
	//					MethodParam param2 = new MethodParam("ByProperty", "", "", auditRuleEntity);
	//					param2.setParams("tableName", tableName);
	//					param2.setParams("auditType", auditType);
	//					param2.setParams("ifStart", "T");
	//					List<AuditRule> aduitRule = memberTempDao.select(param2);
	//					AuditRule ar = null;
	//					if (!Validator.isEmpty(aduitRule)) {
	//						ar = aduitRule.get(0);
	//						// 3.向审核表里插入数据
	//						String auditId = Validator.generate();
	//						Audit newAudit = new Audit();
	//						newAudit.setAuditId(auditId);
	//						newAudit.setCheckUser(ar.getCheckUser());
	//						newAudit.setPid(memberTemp.getMemberId());
	//						newAudit.setNextUser(ar.getNext());
	//						newAudit.setTableName(tableName);
	//						newAudit.setColName("MEMBER_ID");
	//						newAudit.setAuditType(auditType);
	//						newAudit.setAuditsStatus(ConstantData.AuditStatus.AUDITING);
	//						newAudit.setNum(ar.getNum());
	//						newAudit.setCreateTime(DateUtil.getNowTime());
	//						newAudit.setCreateUserEname(loginUser.getUserEname());
	//						newAudit.setUpdateTime(DateUtil.getNowTime());
	//						newAudit.setUpdateUserEname(loginUser.getUserEname());
	//
	//						MethodParam param3 = new MethodParam("Audit", cacheKey, "", auditEntity);
	//						param3.setVaule(newAudit);
	//						//插入成功，更新membertemp的状态,同时向notice表中插入数据
	//						if (memberTempDao.insert(param3)) {
	//							// 4.向notice中插入数据
	//							Notice notice = new Notice();
	//							notice.setNoticeId(auditId);
	//							notice.setFlag("1");
	//							notice.setTitle("会员 [" + memberTemp.getMemberCname() + "] 提交了修改信息申请，请审核。");
	//							notice.setToUser(memberTemp.getClientManager());
	//							MethodParam param4 = new MethodParam("Notice", cacheKey, "", noticeEntity);
	//							param4.setVaule(notice);
	//							if (!memberTempDao.insert(param4)) {
	//								return false;
	//							}
	//							//5.更新memberTemp表
	//
	//							//
	//							memberTemp.setAuditStatus(ConstantData.AuditStatus.AUDITING);
	//							if (!memberTempDao.edit(param)) {
	//								return false;
	//							}
	//							return true;
	//						}
	//					}
	//				}
	//			}
	//		}
	//		return false;
	//	}
}
